import { getLoginInfo, getUserAddrs } from './utils/apis'
import { getCurrentAddress, coordFormat } from './utils/util'
import { gcj02tobd09 } from './utils/coordtransform'
import distance from './utils/distance'
import { host } from './config'
App({
    onLaunch: function() {
        //调用API从本地缓存中获取数据
        var that = this
        var user = wx.getStorageSync('user') || {}
        var userInfo = wx.getStorageSync('userInfo') || {}
        if (
            (!user.openId || (user.expires_in || Date.now()) < Date.now() + 600) &&
            !userInfo.nickName
        ) {

            var count = 1;

            function goGetOpenId() { //获取openId,失败重新获取三次
                wx.login({
                    success: function(res) {
                        if (res.code) {
                            wx.request({
                                url: host + 'u/v1/openId',
                                data: { code: res.code },
                                method: 'GET',
                                success: function(res) {
                                    if (res.data.code == '1000000') {
                                        var obj = {}
                                        obj.wxToken = res.data.wxToken
                                        obj.expires_in = Date.now() + res.data.expires_in
                                        obj.openId = res.data.data.open_id
                                        wx.setStorageSync('user', obj) //存储wxToken
                                        count = 1;
                                    } else {
                                        if (count++ < 3) {
                                            goGetOpenId();
                                        } else {
                                            count = 1;
                                            return
                                        }
                                    }
                                }
                            })
                        } else {
                            console.log('获取用户登录态失败！' + res.errMsg)
                        }
                    }
                })
            }
            goGetOpenId();
        }
    },
    getLoginInfo(cb) {
        var that = this
        if (wx.getStorageSync('loginInfo')) {
            cb && cb(that.globalData.loginInfo)
        } else {
            cb && cb({})
        }
    },
    setLoginInfo(loginInfo) {
        if (loginInfo.token) {
            wx.setStorageSync('loginInfo', loginInfo)
        }
        this.globalData.loginInfo = loginInfo
    },

    // 获取当前地址
    getCurrentAddress(cb) {
        var that = this
        if (this.globalData.currentAddress) {
            return cb && cb(this.globalData.currentAddress)
        }

        getCurrentAddress(address => {
            address = that.setCurrentAddress(address)
            cb(address)
            this.getLoginInfo(loginInfo => {
                if (loginInfo) {
                    this.findNearbyUserAddr(userAddress => {
                        if (!userAddress) {
                            return
                        }
                        that.setCurrentAddress(userAddress)
                    })
                }
            })
        })
    },
    setCurrentAddress(address) {
        if (address.addr_id) {
            address.title = `${address.addr} ${address.detail}`
            address.city = address.city_name
            address.district = address.district_name
            address.location = {
                longitude: address.longitude,
                latitude: address.latitude
            }
        } else {
            address.location = coordFormat(address.location)
        }
        this.globalData.currentAddress = address
        return address
    },

    findNearbyUserAddr(cb, radius = 100) {
        radius /= 100
        wx.getLocation({
            type: 'gcj02',
            success: function(res) {
                var [lng1, lat1] = gcj02tobd09(res.longitude, res.latitude)
                // getUserAddrs(
                //   {
                //     page: 1,
                //     size: 10
                //   }
                // 	{
                //   success(addressList) {
                //     for (let i = 0, len = addressList.length; i < len; i++) {
                //       var address = addressList[i]
                //       var { longitude: lng2, latitude: lat2 } = address
                //       if (distance(lat1, lng1, lat2, lng2) <= radius) {
                //         return cb(address)
                //       }
                //     }
                //     return cb()
                //   }
                // }
                // )
            },
            fail(res) {
                console.log(res.errMsg)
                alert('获取用户地址失败')
            }
        })
    },
    // 同步订单数据
    setQuasiOrder(order_info) {
        Object.assign(this.globalData.order, order_info)
    },

    globalData: {
        order: {},
        loginInfo: wx.getStorageSync('loginInfo') || null,
        currentAddress: null,
        appid: 'wx873c0f4181c9035c',
        secret: '65f0974848180cce49d155857e5894f2'
    }
})